package com.lgh.hotel.handler.security;

import com.lgh.hotel.dao.mapper.SysUserMapper;
import com.lgh.hotel.dao.pojo.SysUser;
import com.lgh.hotel.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("尝试登陆，登录账号：{}",username);
        SysUser sysUser = sysUserService.findUserByUsername(username);
        if (sysUser == null){
            throw new UsernameNotFoundException("数据库无此用户");
        }
        List<GrantedAuthority> grantedAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList(sysUser.getRoles());
        return new User(sysUser.getUsername(),sysUser.getPassword(),grantedAuthorities);
    }
}
